local blaze = require "blaze"
local game = require "club.threecard.sudoku"

local M = game.ui.element()

local StateItem = game.ui.element()


local function update(self)
    local state = self.state
    if not state then
        self.solved_txt.gameObject:SetActive(false)
        self.missed_txt.gameObject:SetActive(false)
        self.cost_txt.gameObject:SetActive(false)
        self.status_txt.gameObject:SetActive(true)
        self.status_txt.text = "未开始"
        return
    end

    local started = state.begin_time and state.begin_time > 0
    local finished = state.end_time and state.end_time > 0
    self.solved_txt.gameObject:SetActive(started)
    self.missed_txt.gameObject:SetActive(started)
    self.cost_txt.gameObject:SetActive(started)
    self.status_txt.gameObject:SetActive(not started)
    if started then
        self.solved_txt.text = string.format("完成：%d/%d", state.solved, state.total)
        self.missed_txt.text = string.format("错误：%d/%d", state.missed, state.max_miss)
        if finished then
            self.cost_txt.text = string.format("耗时：%s", game.i18n.number(state.cost, "elapsed1"))
        else
            self.cost_txt.text = "耗时：进行中"
        end
    end
end

function StateItem:on_injected(bind)
    update(self)
end

function StateItem:set_state(state)
    self.state = state
    update(self)
end

function M:ctor(versus, session, index)
    self.versus = versus
    self.session = session
    self.index = index
    self.res = "club.threecard.sudoku/ui/versus.b:session_item"
    self.left = StateItem.new()
    self.right = StateItem.new()
end

function M:on_injected(bind)
    bind("button.click", self.vs_btn, self.on_vs_click)
    bind("button.click", self.continue_btn, self.on_vs_click)
    local my_user_id = game.kbe.player().user_id
    local result = game.util.versus.analyze_session(self.session, my_user_id)
    local status = self.session.status
    local win = result.win
    local lose = result.lose
    local draw = result.draw

    self.left:set_gameobject(self.my_state_obj, true)
    self.left:set_state(result.me)
    self.right:set_gameobject(self.target_state_obj, true)
    self.right:set_state(result.target)

    self.vs_btn.gameObject:SetActive(status == 0)
    self.continue_btn.gameObject:SetActive(status == 1)
    self.win_btn.gameObject:SetActive(status == 2 and win)
    self.lose_btn.gameObject:SetActive(status == 2 and lose)
    self.draw_btn.gameObject:SetActive(status == 2 and draw)
end

function M:on_vs_click()
    game.audio.post("click")
    local session_key = string.format("%s-%s", self.versus.id, self.session.id)
    game.kbe.player().async_game_api:start(session_key)
    :next(function()
        game.game_scene.enter(self.versus.room_config_id)
    end)
end

return M